package com.ayf.payment.game.api.controller;

import com.ayf.payment.game.api.cache.redis.RedisCacheUtil;
import com.ayf.payment.game.api.dto.MerchantDTO;
import com.ayf.payment.game.api.dto.criteria.MerchantCriteria;
import com.ayf.payment.game.api.entity.Merchant;
import com.ayf.payment.game.api.exception.ParameterException;
import com.ayf.payment.game.api.mail.EmailParam;
import com.ayf.payment.game.api.mail.EmailUtils;
import com.ayf.payment.game.api.service.MerchantService;
import com.ayf.payment.game.api.sms.SMSUtil;
import com.ayf.payment.game.api.type.CommonConstants;
import com.ayf.payment.game.api.type.SMSType;
import com.ayf.payment.game.api.utils.*;
import com.swwx.charm.commons.lang.utils.LogPortal;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description:
 * @Author: zh-liang
 * @Date : 2020-03-12 11:37
 */
@RestController
@RequestMapping("/code")
public class VerifyCodeController {

    @Autowired
    private RedisCacheUtil redisCacheUtil;

    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    private EmailUtils sendEmailUtils;

    @Autowired
    private SMSUtil smsUtil;

    @Autowired
    private MerchantService merchantService;

    /**
     * 获取随机验证码
     *
     * @param response
     * @return
     * @throws Exception
     */
    @GetMapping("/randomVerifyCode")
    public void randomVerifyCode(HttpServletResponse response) {
        //设置相应类型,告诉浏览器输出的内容为图片
        response.setContentType("image/jpeg");
        //设置响应头信息，告诉浏览器不要缓存此内容
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expire", 0);
        //输出验证码图片
        String id = TokenUtils.genAccessToken();
        Cookie cookie = new Cookie("codeKey", id);
        cookie.setPath("/");
        response.addCookie(cookie);
        try {
            String randomCode = VerifyCodeUtil.outputVerifyImage(response);
            redisCacheUtil.setObjectToCacheDelaySeconds(id, randomCode, (long) (60));
        } catch (Exception e) {
            LogPortal.error("验证码输出到客户端失败,session id[{}],发生[{}]异常", e, id, e.getMessage());
        }
    }

    /**
     * 发送邮箱验证码
     *
     * @return
     */
    @PostMapping("/emailVerifyCode")
    public CommonResult emailVerifyCode(@RequestBody MerchantCriteria merchantCriteria) {
        if (merchantCriteria == null || StringUtils.isBlank(merchantCriteria.getEmail())) {
            throw new ParameterException("邮箱不能为空");
        }
        String code = RandomStrUtils.createRandom(true, 6);
        try {
            EmailParam emailParam = new EmailParam();
            redisCacheUtil.setObjectToCacheDelaySeconds(merchantCriteria.getEmail(), code, (long) (60 * 30));
            emailParam.setCode(code);
            String[] to = new String[1];
            to[0] = merchantCriteria.getEmail();
            sendEmailUtils.sendThymeleafEmail(from, to, "游戏平台-验证码", emailParam, "email/EmailValida");
            LogPortal.info("邮箱[{}]发送邮箱验证码[{}]成功", merchantCriteria.getEmail(), code);
        } catch (Exception e) {
            LogPortal.error("邮箱[{}]发送邮箱验证码[{}]时发生[{}]异常", e, merchantCriteria.getEmail(), code, e.getMessage());
            return new CommonResult<>(CommonConstants.RETURN_ERROR, "发送邮箱验证码失败");
        }
        return new CommonResult<>(CommonConstants.RETURN_SUCCESS, "发送邮箱验证码成功");
    }

    /**
     * 发送短信验证码
     *
     * @return
     */
    @PostMapping("/sms")
    public CommonResult register(@CookieValue("codeKey") String codeKey,
                                 @RequestBody MerchantCriteria merchantCriteria) {
        if (StringUtils.isBlank(merchantCriteria.getPhone())) {
            throw new ParameterException("手机号不能为空");
        }
        if (StringUtils.isBlank(merchantCriteria.getCode())) {
            throw new ParameterException("图片验证码不能为空");
        }
        String code = redisCacheUtil.getObjectFromCache(codeKey);
        //验证验证码
        if (!merchantCriteria.getCode().equalsIgnoreCase(code)) {
            return new CommonResult(CommonConstants.RETURN_ERROR, "图片验证码输入错误");
        }
        smsUtil.send(merchantCriteria.getPhone(), merchantCriteria.getSmsType());
        return new CommonResult(CommonConstants.RETURN_SUCCESS, "发短信验证码成功");
    }

    /**
     * 发送短信验证码
     *
     * @return
     */
    @PostMapping("/smsMer")
    public CommonResult smsMer(@CookieValue("codeKey") String codeKey, @RequestBody MerchantCriteria merchantCriteria) {
        if (StringUtils.isBlank(merchantCriteria.getLoginAccount())) {
            throw new ParameterException("账号不能为空");
        }
        if (StringUtils.isBlank(merchantCriteria.getCode())) {
            throw new ParameterException("图片验证码不能为空");
        }
        String code = redisCacheUtil.getObjectFromCache(codeKey);
        //验证验证码
        if (!merchantCriteria.getCode().equalsIgnoreCase(code)) {
            return new CommonResult(CommonConstants.RETURN_ERROR, "图片验证码输入错误");
        }
        Merchant merchant = new Merchant();
        merchant.setLoginAccount(merchantCriteria.getLoginAccount());
        MerchantDTO merchantDTO = merchantService.selectOne(merchant);
        if (merchantDTO == null) {
            return new CommonResult(CommonConstants.RETURN_ERROR, "该商户不存在，请确认登录账号");
        }
        smsUtil.send(merchantDTO.getPhone(), SMSType.LOGIN,merchantDTO.getId());
        return new CommonResult(CommonConstants.RETURN_SUCCESS,
                "短信验证码成功发送到:"+ SensitiveDataUtil.mobileEncrypt(merchantDTO.getPhone()));
    }
}
